<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebRTC 修复测试</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/6.0.1/signalr.min.js"></script>
    <style>
        body { font-family: Arial, sans-serif; padding: 20px; }
        .log { background: #f0f0f0; padding: 10px; margin: 10px 0; height: 200px; overflow-y: auto; }
        button { margin: 5px; padding: 10px; }
        input { margin: 5px; padding: 5px; }
    </style>
</head>
<body>
    <h1>WebRTC 修复测试</h1>
    
    <div>
        <h3>用户加入测试</h3>
        <input type="text" id="testUserName" placeholder="测试用户名" value="TestUser123">
        <button onclick="testJoinUser()">测试加入用户</button>
        <button onclick="showCurrentState()">显示当前状态</button>
    </div>
    
    <div>
        <h3>房间创建测试</h3>
        <input type="text" id="testRoomName" placeholder="测试房间名" value="TestRoom123">
        <button onclick="testCreateRoom()">测试创建房间</button>
    </div>
    
    <div>
        <h3>测试日志</h3>
        <div id="testLog" class="log"></div>
        <button onclick="clearLog()">清空日志</button>
    </div>

    <script>
        let connection = null;
        let currentUserId = null;
        let currentUserName = null;

        // 初始化连接
        async function initConnection() {
            connection = new signalR.HubConnectionBuilder()
                .withUrl("https://localhost:5001/signaling")
                .withAutomaticReconnect()
                .configureLogging(signalR.LogLevel.Information)
                .build();

            // 注册事件处理器
            connection.on("UserJoined", (data) => {
                log(`收到 UserJoined 事件: ${JSON.stringify(data)}`, 'info');
                
                if (!currentUserId && data.UserId) {
                    currentUserId = data.UserId;
                    currentUserName = data.UserName;
                    log(`✅ 用户状态已保存: currentUserId = ${currentUserId}`, 'success');
                } else {
                    log(`⚠️ UserJoined 事件被跳过: currentUserId=${currentUserId}, eventUserId=${data.UserId}`, 'warning');
                }
            });

            connection.on("RoomCreated", (data) => {
                log(`✅ 房间创建成功: ${JSON.stringify(data)}`, 'success');
            });

            connection.on("Error", (message) => {
                log(`❌ 服务器错误: ${message}`, 'error');
            });

            try {
                await connection.start();
                log(`✅ SignalR 连接成功`, 'success');
            } catch (err) {
                log(`❌ SignalR 连接失败: ${err}`, 'error');
            }
        }

        // 测试加入用户
        async function testJoinUser() {
            const userName = document.getElementById('testUserName').value.trim();
            if (!userName) {
                log('❌ 请输入用户名', 'error');
                return;
            }

            log(`🚀 开始测试加入用户: ${userName}`, 'info');
            log(`📊 调用前状态: currentUserId = ${currentUserId}`, 'debug');

            try {
                await connection.invoke("JoinUser", userName);
                log(`📡 JoinUser 调用完成，等待事件响应...`, 'debug');
                
                // 检查状态
                setTimeout(() => {
                    if (currentUserId) {
                        log(`✅ 测试成功！用户 ${userName} 已加入，ID: ${currentUserId}`, 'success');
                    } else {
                        log(`❌ 测试失败！JoinUser 调用后 currentUserId 仍为 null`, 'error');
                    }
                }, 1000);
                
            } catch (err) {
                log(`❌ JoinUser 调用失败: ${err}`, 'error');
            }
        }

        // 测试创建房间
        async function testCreateRoom() {
            const roomName = document.getElementById('testRoomName').value.trim();
            if (!roomName) {
                log('❌ 请输入房间名称', 'error');
                return;
            }

            log(`🚀 开始测试创建房间: ${roomName}`, 'info');
            log(`📊 调用前状态: currentUserId = ${currentUserId}`, 'debug');

            if (!currentUserId) {
                log('❌ 无法创建房间：用户尚未加入系统', 'error');
                return;
            }

            try {
                await connection.invoke("CreateRoom", roomName);
                log(`✅ CreateRoom 调用完成，房间名: ${roomName}`, 'success');
            } catch (err) {
                log(`❌ CreateRoom 调用失败: ${err}`, 'error');
            }
        }

        // 显示当前状态
        function showCurrentState() {
            log(`📊 当前状态报告:`, 'info');
            log(`   - Connection State: ${connection?.state || 'null'}`, 'debug');
            log(`   - Current User ID: ${currentUserId || 'null'}`, 'debug');
            log(`   - Current User Name: ${currentUserName || 'null'}`, 'debug');
        }

        // 日志函数
        function log(message, type = 'info') {
            const logDiv = document.getElementById('testLog');
            const timestamp = new Date().toLocaleTimeString();
            const colors = {
                'success': '#28a745',
                'error': '#dc3545',
                'warning': '#ffc107',
                'info': '#17a2b8',
                'debug': '#6c757d'
            };
            
            const logEntry = document.createElement('div');
            logEntry.style.color = colors[type] || '#000';
            logEntry.innerHTML = `[${timestamp}] ${message}`;
            
            logDiv.appendChild(logEntry);
            logDiv.scrollTop = logDiv.scrollHeight;
            
            console.log(`[${type.toUpperCase()}] ${message}`);
        }

        // 清空日志
        function clearLog() {
            document.getElementById('testLog').innerHTML = '';
        }

        // 页面加载时初始化
        window.addEventListener('load', initConnection);
    </script>
</body>
</html> 